package cn.lili.init;

import cn.lili.common.properties.ApiProperties;
import cn.lili.modules.payment.kit.plugin.wechat.WechatV3Api;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.payment.WechatPaymentSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.modules.system.service.SettingService;
import com.alibaba.fastjson.JSON;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class WechatInitRunner implements ApplicationRunner {
    @Autowired
    private ApiProperties apiProperties;

    @Autowired
    private SettingService settingService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            WechatV3Api.init();
//            Ret deleteComplaintNotifications = WechatV3Api.deleteComplaintNotifications();
//            log.info("删除投诉回调链接：{}", deleteComplaintNotifications);
//            Ret addComplaintNotifications = WechatV3Api.addComplaintNotifications(apiProperties.getBuyer().replace("http://", "https://") + "/buyer/payment/so/notify/WECHAT/complaint");
//            log.info("添加投诉回调链接：{}", addComplaintNotifications);

            Setting systemSetting = settingService.get(SettingEnum.WECHAT_PAYMENT.name());
            WechatPaymentSetting setting = JSON.parseObject(systemSetting.getSettingValue()).toJavaObject(WechatPaymentSetting.class);
            ApiConfig ac = new ApiConfig();
            ac.setAppId(setting.getAppId());
            ac.setAppSecret(setting.getSecret());
            ac.setToken(setting.getToken());
            log.info("初始化微信配置：" + ac.getAppId() + " " + ac.getAppSecret() + " " + ac.getToken());
            ApiConfigKit.putApiConfig(ac);
        } catch (Exception e) {
            log.error("微信V3接口初始化失败", e);
        }
    }

}
